package com.googlecode.afdbaccess.web.portal.webcontent.js.common_login_data;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.jboss.resteasy.annotations.cache.Cache;

import com.googlecode.afdbaccess.web.common.interceptors.RequestLogged;
import com.googlecode.afdbaccess.web.common.json.ExtJsJsonResponse;
import com.googlecode.afdbaccess.web.common.login.ApplicationPrincipal;

@RequestLogged
@Path("js/common-login-data")
public class LoginGetRest {
    @JsonSerialize(include = Inclusion.NON_NULL)
    private class Data {
        boolean loggedIn;
        String userName;
        String displayName;
        private final List<String> hasRoles = new ArrayList<String>();

        @SuppressWarnings("unused")
        public boolean isLoggedIn() {
            return this.loggedIn;
        }
        @SuppressWarnings("unused")
        public String getUserName() {
            return this.userName;
        }
        @SuppressWarnings("unused")
        public String getDisplayName() {
            return this.displayName;
        }
        @SuppressWarnings("unused")
        public List<String> getHasRoles() {
            return this.hasRoles;
        }
        
        //
        
        void addRole(String role) {
            this.hasRoles.add(role);
        }
    }
    
    @GET
    @Cache(isPrivate=true, maxAge=0)
    @Produces("application/json")
    public ExtJsJsonResponse get(@SuppressWarnings("unused") @Context HttpServletRequest request, @Context SecurityContext securityContext) {
        Data jsonData = new Data();
        jsonData.loggedIn = securityContext.getUserPrincipal() != null;
        if (securityContext.getUserPrincipal() != null) {
            ApplicationPrincipal applicationPrincipal = (ApplicationPrincipal)securityContext.getUserPrincipal();
            jsonData.userName = applicationPrincipal.getName();
            jsonData.displayName = applicationPrincipal.getDisplayName();
            setRoles(jsonData, securityContext);
        }
        
        return new ExtJsJsonResponse(jsonData);
    }

    private static void setRoles(Data data, SecurityContext securityContext) {
        String[] allRoles = { "theRole" };
        
        for(String potentialRole: allRoles) {
            if(securityContext.isUserInRole(potentialRole)) {
                data.addRole(potentialRole);
            }
        }
    }
}
